<template>
  <n-modal v-model:show="visible" :title="title" display-directive="if" :bordered="false" preset="card" class="w-500px"  size="huge" :closable="false" >
    <n-form :model="formData" ref="formRef" :rules="rules"  :label-width="80"  label-placement="left" class="fi-w">
      <n-form-item label="登录名" path="userName">
        <n-input v-model:value="formData.userName" />
      </n-form-item>
      <n-form-item label="昵称" path="nickName">
        <n-input v-model:value="formData.nickName" />
      </n-form-item>
      <n-form-item label="手机号" path="phone">
        <n-input v-model:value="formData.phone" />
      </n-form-item>
      <n-form-item label="邮箱" path="email">
        <n-input v-model:value="formData.email" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input type="password" v-model:value="formData.password" :disabled="!!formData.id" />
      </n-form-item>
      <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="formData.sex">
              <n-space>
                  <n-radio label="男" value="0" />
                  <n-radio label="女" value="1" />
              </n-space>
          </n-radio-group>
      </n-form-item>
      <n-form-item label="所属部门" path="deptId">
          <n-cascader :options="deptTree" label-field="name" value-field="id" children-field="children" filterable
          v-model:value="formData.deptId" clearable  :default-expand-all="true" expand-trigger="hover" check-strategy="child"/>
      </n-form-item>
        <n-form-item label="角色" path="roleIds">
          <n-select v-model:value="formData.roleIds" multiple :options="obj2any(roleSelect)" label-field="roleName"  value-field="id" />
      </n-form-item>
      <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
              <n-space>
                  <n-radio label="启用" :value="BusinessStatus.Yes" />
                  <n-radio label="禁用" :value="BusinessStatus.No" />
              </n-space>
          </n-radio-group>
      </n-form-item>
    </n-form>
      <n-space justify="center">
          <n-button type="primary"  @click="handleSubmitForm">确定</n-button>
          <n-button @click="handleCloseModal">取消</n-button>
      </n-space>
  </n-modal>
</template>

<script  setup lang='ts' >
import { toRefs, ref ,onMounted, computed, reactive, watch  } from 'vue';
import { BusinessStatus } from "@/enum";
import { fetchUpdateUser,fetchAddUser, fetchUser} from '@/service/api/sys/user'
import { fetchDeptTree } from '@/service/api/sys/dept'
import { fetchRoleSelect } from '@/service/api/sys/role'
import { FormRules } from 'naive-ui';
import {obj2any} from "@/utils/common"
import { FlatResponseData } from '~/packages/axios/src/type';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';

interface DataSource extends SysAuth.UserInfo { }
type Props = {
    visible:boolean,
    operateType:NaiveUI.TableOperateType,
    editKey?:Common.IdType | null
  }
const props = defineProps<Props>()
const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增',
    edit: '编辑'
  };
  return titles[props.operateType];
});
const editKey = computed(() => props.editKey || null);

interface Emits {
  (e: 'submitted'): void;
}
const emit = defineEmits<Emits>();




const deptTree = ref<any|null>()
const roleSelect = ref<SysAuth.RoleInfo[]>()

const { formRef, validate, restoreValidation } = useNaiveForm();
const { patternRules } = useFormRules();

const formData = ref<DataSource>(initFormData());

const rules: FormRules = {
  password: patternRules.pwd,
  userName:{ required: true, message: "请输入登录名", trigger: 'input' },
  nickName:{ required: true, message: "请输入昵称", trigger: 'input' }
};
function initFormData():DataSource{
    return {
				userName:"",
        status:BusinessStatus.No,
    }
}

function handleCloseModal() {
  visible.value = false;
  emit("submitted")
}
function handleFetchResult(res: FlatResponseData<any, App.Service.Response<unknown>>) {
    if (!res.error) {
      window.$message?.success("操作成功");
      handleCloseModal()
    }
}
async function handleSubmitForm() {
    await validate()

    if(!formData.value.deptId){
      window.$message?.error("部门不能为空！")
      return false;
    }
    if (formData.value.id) {
        fetchUpdateUser(formData.value).then(handleFetchResult)
    } else {
        fetchAddUser(formData.value).then(handleFetchResult)
    }
}
async function initEditData(){
  if(props.operateType === 'edit' && editKey.value !== null){
    const { data } = await fetchUser(editKey.value)
     formData.value = data!;
    }
}

async function getRoleSelect (){
	const {data} = await fetchRoleSelect()
	roleSelect.value = data!
}
async function getDeptTree(){
	const {data} = await fetchDeptTree();
	deptTree.value = data
}

watch(visible, () => {
  if (visible.value) {
    restoreValidation()
    initEditData();
    getDeptTree();
	  getRoleSelect();
  }else{
    formData.value = initFormData()
  }
});

</script>

